//
//  WBRefreshView.swift
//  WeiBo
//
//  Created by chenguanglei on 16/12/2.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit


enum RefreshStatus: Int {
    case normal = 1000
    case pulling = 2000
    case loading = 3000
}


private let WBRefreshViewHeight: CGFloat = 44

class WBRefreshView: UIControl {

    var scrollView : UIScrollView?
    
    
    var status: RefreshStatus = .normal{
    
        didSet{
        
            
            switch status {
            case .normal:
                print("处理正常逻辑")
                messageLabel.text = "下拉刷新"
                
                arrowTurn(flag: true)
                
                loadingView.isHidden = true
                
                arrowImageView.isHidden = false
                
                
            case .pulling:
                print("释放更新")
                messageLabel.text = "释放更新"
                
                arrowTurn(flag: true)
                
            case .loading:
                print("加载数据")
                
                var inset = scrollView!.contentInset
                
                inset.top = inset.top + WBRefreshViewHeight
                
                scrollView?.contentInset = inset
                
                messageLabel.text = "加载中"
                
                arrowImageView.isHidden = true
                
                loadingView.isHidden = false
                
                loadingView.startAnimating()
                
                sendActions(for: UIControlEvents.valueChanged)
            
            }
            
        
        
        }
    
    
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
    
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        if newSuperview is UIScrollView {
            
            scrollView = newSuperview as? UIScrollView
            
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
            
        }
        
    }
    
    
    private func arrowTurn(flag:Bool){
    
        let rotate = flag ? (M_PI - 0.01) : (M_PI + 0.01)
        
        UIView.animate(withDuration: 0.25) { 
            
            self.arrowImageView.transform = self.arrowImageView.transform.rotated(by: CGFloat(rotate))
            
        }
    
    }
    
    
    func endRefreshing(){
    
        if status == .loading {
            
            var inset = scrollView!.contentInset
            
            inset.top = inset.top - WBRefreshViewHeight
            
            scrollView?.contentInset = inset
        }
        
        status = .normal
       
    }
    
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let offsetY = scrollView?.contentOffset.y else {
            return
        }
        
        if scrollView!.isDragging {
            
            if offsetY < -140&&status == .normal{
                
                status = .pulling
                
            } else if offsetY >= -140&&status == .pulling{
            
            status = .normal
            
            }
            
            
        }else{
        
            if offsetY < -140&&status == .pulling{
                
                status = .loading
                
            }
        
        
        }
        
        
        
    }
    
    
    
    
    
    
    private func setupUI(){
    
        backgroundColor = RandomColor()
        
        self.frame.size = CGSize.init(width: kUIScreenWidth, height: WBRefreshViewHeight)
    
        self.frame.origin.y = -WBRefreshViewHeight
        
        addSubview(arrowImageView)
        addSubview(messageLabel)
        addSubview(loadingView)
        
        arrowImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLabel.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(10)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        loadingView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        
        
    }
    
    
    private lazy var arrowImageView: UIImageView = UIImageView(image:UIImage(named: "tableview_pull_refresh"))
    
    private lazy var messageLabel: UILabel = UILabel(labelText: "下拉刷新", labelFont: 15, textColor: UIColor.darkGray, align: NSTextAlignment.center)
    
    private lazy var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
}
